package com.hippo.core.vm

import android.content.Context
import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import com.hippo.core.state.DownloadState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import com.hippo.core.config.AppStoreKey
import com.hippo.core.core.manager.AppStore
import com.hippo.core.core.manager.FileDownloader
import com.hippo.core.core.manager.FileManager
import com.hippo.core.utils.UiHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import com.hippo.core.R

class DownloadVM : ViewModel() {

    var uiState by mutableStateOf(DownloadState())


    fun downloadPdf(context:Context) {
        val url = AppStore.readString(AppStoreKey.pdfUrl,null)
        uiState = uiState.copy(
            isDownloading = true,
            downloadUrl = url
        )

        if (url != null) {
            viewModelScope.launch(Dispatchers.IO) {
                try {
                    val path = FileManager.getDownloadPath(context) +"/"+url.substringAfterLast('/')
                    FileDownloader.download(url, File(path), {progress, current, total ->
                        val downloadProgress = progress.toInt()
                        Log.i("DownloadVM", "downloadPdf: $downloadProgress")
                        uiState = uiState.copy(
                            downloadProgress = downloadProgress,
                            downloadComplete = downloadProgress != 100
                        )
                    },{
                        uiState = uiState.copy(
                            isDownloading = false,
                        )
                        UiHandler.showToast(R.string.spt_11)
                    })
                }catch (e: Exception){
                    e.printStackTrace()
                    uiState = uiState.copy(
                        isDownloading = false,
                    )
                    UiHandler.showToast(R.string.spt_11)
                }

            }
        }
    }

    fun updateUiState(state:DownloadState) {
        uiState = state
    }


}